package com.pojoin.cms.face;

import java.util.Set;

import org.springframework.beans.BeanUtils;

import com.pojoin.cms.dao.ResourceDao;
import com.pojoin.cms.domain.Resource;
import com.pojoin.cms.domain.Role;
import com.pojoin.cms.domain.alter.ResourceAlter;
import com.pojoin.cms.domain.form.ResourceForm;
import com.pojoin.cms.exception.CmsException;
import com.pojoin.cms.util.SpringContext;

public class ResourceFaceLocal extends ResourceAlter implements ResourceFace {
	
	private ResourceDao resourceDao;

	public void setResourceDao(ResourceDao resourceDao) {
		this.resourceDao = resourceDao;
	}

	@Override
	public boolean isPersistenceAvailable() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void delete() throws CmsException {
		RoleFaceFactory rff = (RoleFaceFactory) SpringContext.getBean("roleFaceFactory");
		Set<Role> roleSet = this.getRoles();
		String owerId = this.resourceId.toString();
		for(Role role : roleSet){
			RoleFace rf = rff.getRoleFaceById(role.getRoleId());
			Set<Resource> resourceSet = role.getResources();
			String resourceIds = "";
			for(Resource r : resourceSet){
				if(!r.getResourceId().toString().equals(owerId)){
					resourceIds += r.getResourceId() + ",";
				}
			}
			rf.resetResources(resourceIds);
			rf.flush();
			rf = null;
			resourceSet = null;
			
		}
		this.resourceDao.delById(this.resourceId);
		owerId = null;
		roleSet = null;
		rff = null;
	}

	@Override
	public void flush() throws CmsException {
		this.resourceDao.update(this);

	}

	@Override
	public void reload() throws CmsException {
		Resource r = this.resourceDao.findById(this.resourceId);
		BeanUtils.copyProperties(r, this);
	}

	public void setResourceId(Long resourceId) {
		this.resourceId = resourceId;
	}

	@Override
	public void update(ResourceForm resource) {
		BeanUtils.copyProperties(resource, this);
		
	}

}
